<?php
defined('__JF')
		or die('Direct access is not allowed');

/**
 *
 * For example:
 * <pre>
 *
 * </pre>
 *
 * @author 	Yernat Assanov
 * @version 0.1
 */
final class JF_FileUtil
{

	const sRoot = JF_ROOT;

	public static function exists($sFilepath) {
		return self::is(self::getFilepath($sFilepath));
	}

	public static function read($sFilepath, $sMode = 'rt') {
		$sFilepath = self::getFilepath($sFilepath);
		if (!in_array($sMode, array('rt', 'rb'))) {
			$sMode = 'rt';
		}

		if (self::is($sFilepath) == true) {
			if ($rLink = @fopen($sFilepath, $sMode)) {
				flock($rLink, LOCK_SH);
			 	$sData = @fread($rLink, filesize($sFilepath));
				flock($rLink, LOCK_UN);
			 	fclose($rLink);
				return $sData;
			}
			else {
				throw new JF_IOException('Cant read file ' . $sFilepath);
			}

		}
		else {
			throw new JF_IOException('File not exists ' . $sFilepath);
		}

	}

	public static function write($sFilepath, $sData, $sMode = 'w') {
		$sFilepath = self::getFilepath($sFilepath);
		if (!in_array($sMode, array('r+', 'w', 'w+', 'a', 'a+'))) {
			$sMode = 'w';
		}

		if (self::is($sFilepath) == true) {
			if ($rLink =@ fopen($sFilepath, $sMode)) {
				flock($rLink, LOCK_EX);
				set_file_buffer($rLink, 0);
				@fwrite($rLink, $sData);
				fflush($rLink);
				flock($rLink, LOCK_UN);
				fclose($rLink);
			}
			else {
				throw new JF_IOException('Cant write to file ' . $sFilepath);
			}

		}
		else {
			throw new JF_IOException('File not exists ' . $sFilepath);
		}

	}

	public static function load($sClasspath) {
		$sClasspath = self::getFilepath($sClasspath);
		if (self::is($sClasspath)) {
			include_once $sClasspath;
		}
		else {
			throw new JF_IOException('File not exists ' . $sClasspath);
		}

	}

	private static function getFilepath($sFilepath) {
		return self::sRoot . '/' . $sFilepath;
	}


	private static function is($sFilepath) {
		if (strlen($sFilepath) > 0) {
			return ((file_exists($sFilepath) == true) && (is_readable($sFilepath) == true));
		}
		else {
			return false;
		}

	}

}